﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MyFloridaHouse.libPrint.KML;
using System.Text;
using MyFloridaHouse.libPrint.BingMapAjaxHelpers;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;
using MyFloridaHouse.libPrint.MapBaseLayers;
using ICSharpCode.SharpZipLib.Core;

namespace MyFloridaHouse.MapServer
{
    public partial class PrintView : System.Web.UI.Page
    {
        public string javaScriptString;
        public kml kmlDeserialized;
        public StringBuilder builder = new StringBuilder();
        public string bingKey = ""; //removed this to checkin
        /// <summary>
        /// Converts the KML to bing ajax via parsing methodology.
        /// </summary>
        /// <param name="myString">My string.</param>
        /// <returns></returns>
        public void ConvertKMLToBingAjax()
        {

            StringBuilder builder = new StringBuilder();
            //turn print view status notice
            builder.Append("document.getElementById(\"prtViewStatusDiv\").innerHTML ='<H3>Please wait while Print View is loading!</H3>';");

            //turn off the file picker
            builder.Append("document.getElementById(\"fileControlDiv\").style.display='none';");


            //main map----------------------------------------------------------
            Point[] mainMapBoxPts = new Point[2];
            mainMapBoxPts[0] = new Point(-87.73681640625, 31.034108344903487);
            mainMapBoxPts[1] = new Point(-79.69482421875, 24.487148563173438);
            builder.Append("var map = null;");
            builder.Append("var polygoncolor;");
            //builder.Append("var polygon;");
            builder.Append("var mapOptions;");
            builder.Append("var mainMap;");
            //builder.Append("var vertices;");
            builder.Append("var boundBoxVertices;");
            builder.Append("var m = Microsoft.Maps;");
            builder.Append("var mainMap = new Microsoft.Maps.Map(document.getElementById(\"MainMap\"),");
            builder.Append("{ credentials: \"" + bingKey + "\",");
            builder.Append("center: new Microsoft.Maps.Location(26.5, -84.0),");
            builder.Append("zoom: 7,");
            builder.Append("animate: false,");
            builder.Append("showCopyright: false,");
            builder.Append("showDashboard: false,");
            builder.Append("disableMouseInput: true,");
            builder.Append("showScalebar: false,");
            builder.Append("enableSearchLogo: false,");
            builder.Append("enableClickableLogo: false,");
            //builder.Append("padding: 0});");
            builder.Append("padding: 0,");
            builder.Append("mapTypeId: m.MapTypeId.mercator});"); //to hide the bing map
            //KMLParser kmlParser = new KMLParser(iKML, "mainMap", mainMapBoxPts);
            builder.Append("AddPoly1(mainMap);");
            string mainMapJavaScript = JavaScriptBuilder.GetDistrictsJavaScript("mainMap", false, kmlDeserialized, 9);
            builder.Append(mainMapJavaScript);
            //get map base layers here
            //builder.Append("AddCountyPoly1(mainMap);");
            kmlDocument countyBaseLayersKml = GetCountiesBaseLayers();
            string countyMainMapJavascript = JavaScriptBuilder.GetMainMapCountiesJavaScript("mainMap", countyBaseLayersKml, 9);
            builder.Append(countyMainMapJavascript);
            builder.Append("function AddCountyPoly68(){document.getElementById(\"prtViewStatusDiv\").style.display='none';window.print();}");

            //Add the gold coast inset 
            Point[] goldCoastMapBoxPts = new Point[2];
            goldCoastMapBoxPts[0] = new Point(-80.55, 26.68);
            goldCoastMapBoxPts[1] = new Point(-79.9, 25.43);
            builder.Append("var goldCoastMap = new Microsoft.Maps.Map(document.getElementById(\"GoldCoastMap\"),");
            builder.Append("{ credentials: \"" + bingKey + "\",");
            builder.Append("center: new Microsoft.Maps.Location(26.055000007152557, -80.225000001490116),");
            builder.Append("zoom: 9,");
            builder.Append("animate: false,");
            builder.Append("showCopyright: false,");
            builder.Append("showDashboard: false,");
            builder.Append("disableMouseInput: true,");
            builder.Append("showScalebar: false,");
            builder.Append("enableSearchLogo: false,");
            builder.Append("enableClickableLogo: false,");
            builder.Append("padding: 0,");
            builder.Append("mapTypeId: m.MapTypeId.mercator});"); //to hide the bing map
            string goldCoastMapJavaScript = JavaScriptBuilder.GetMapInsetDistrictsJavaScript("goldCoastMap", goldCoastMapBoxPts, kmlDeserialized);
            builder.Append(goldCoastMapJavaScript);
            string countyGoldCoastMapJavascript = JavaScriptBuilder.GetMapInsetCountiesJavaScript("goldCoastMap", goldCoastMapBoxPts, countyBaseLayersKml);
            builder.Append(countyGoldCoastMapJavascript);

            ////Add the jax coast inset----------------------------------------------------
            Point[] jaxMapBoxPts = new Point[2];
            jaxMapBoxPts[0] = new Point(-82.6, 30.7);
            jaxMapBoxPts[1] = new Point(-81.232, 29.821);
            //jaxMapBoxPts[0] = new Point(-82.008, 30.578);
            //jaxMapBoxPts[1] = new Point(-81.351, 30.126);
            builder.Append("var jaxMap = new Microsoft.Maps.Map(document.getElementById(\"JaxMap\"),");
            builder.Append("{ credentials: \"" + bingKey + "\",");
            //POINT (-81.86599999666214 30.260499998927116)
            //builder.Append("center: new Microsoft.Maps.Location(30.260499998927116, -81.86599999666214),");
            builder.Append("center: new Microsoft.Maps.Location(30.29, -81.657407),");
            builder.Append("zoom: 9,");
            builder.Append("animate: false,");
            builder.Append("showCopyright: false,");
            builder.Append("showDashboard: false,");
            builder.Append("disableMouseInput: false,");
            builder.Append("showScalebar: false,");
            builder.Append("enableSearchLogo: false,");
            builder.Append("enableClickableLogo: false,");
            builder.Append("padding: 0,");
            builder.Append("mapTypeId: m.MapTypeId.mercator});"); //to hide the bing map
            string jaxMapJavaScript = JavaScriptBuilder.GetMapInsetDistrictsJavaScript("jaxMap", jaxMapBoxPts, kmlDeserialized);
            builder.Append(jaxMapJavaScript);
            string countyJaxMapJavascript = JavaScriptBuilder.GetMapInsetCountiesJavaScript("jaxMap", jaxMapBoxPts, countyBaseLayersKml);
            builder.Append(countyJaxMapJavascript);

            //Add orlando map inset
            Point[] orlandoMapBoxPts = new Point[2];
            //28.645264 / -81.554571
            orlandoMapBoxPts[0] = new Point(-82.20, 28.99);
            //28.432933 / -80.877814
            orlandoMapBoxPts[1] = new Point(-80.477814, 28.2);
            builder.Append("var orlandoMap = new Microsoft.Maps.Map(document.getElementById(\"OrlandoMap\"),");
            builder.Append("{ credentials: \"" + bingKey + "\",");
            //POINT (-81.338906988501549 28.594999998807907)
            builder.Append("center: new Microsoft.Maps.Location(28.594999998807907, -81.338906988501549),");
            builder.Append("zoom: 8,");
            builder.Append("animate: false,");
            builder.Append("showCopyright: false,");
            builder.Append("showDashboard: false,");
            builder.Append("disableMouseInput: false,");
            builder.Append("showScalebar: false,");
            builder.Append("enableSearchLogo: false,");
            builder.Append("enableClickableLogo: false,");
            builder.Append("padding: 0,");
            builder.Append("mapTypeId: m.MapTypeId.mercator});"); //to hide the bing map
            string orlandoMapJavaScript = JavaScriptBuilder.GetMapInsetDistrictsJavaScript("orlandoMap", orlandoMapBoxPts, kmlDeserialized);
            builder.Append(orlandoMapJavaScript);
            string countyOrlandoMapJavascript = JavaScriptBuilder.GetMapInsetCountiesJavaScript("orlandoMap", orlandoMapBoxPts, countyBaseLayersKml);
            builder.Append(countyOrlandoMapJavascript);

            //Add Tampa map inset
            Point[] tampaMapBoxPts = new Point[2];
            //28.001893 / -82.829372
            tampaMapBoxPts[0] = new Point(-83.1, 28.5);
            //27.734808 / -82.378933
            tampaMapBoxPts[1] = new Point(-81.1, 27.6);
            builder.Append("var tampaMap = new Microsoft.Maps.Map(document.getElementById(\"TampaMap\"),");
            builder.Append("{ credentials: \"" + bingKey + "\",");
            //POINT (-82.099999994039536 28.049999997019768)
            builder.Append("center: new Microsoft.Maps.Location(28.049999997019768, -82.099999994039536),");
            builder.Append("zoom: 8,");
            builder.Append("animate: false,");
            builder.Append("showCopyright: false,");
            builder.Append("showDashboard: false,");
            builder.Append("disableMouseInput: false,");
            builder.Append("showScalebar: false,");
            builder.Append("enableSearchLogo: false,");
            builder.Append("enableClickableLogo: false,");
            builder.Append("padding: 0,");
            builder.Append("mapTypeId: m.MapTypeId.mercator});"); //to hide the bing map
            string tampaMapJavaScript = JavaScriptBuilder.GetMapInsetDistrictsJavaScript("tampaMap", tampaMapBoxPts, kmlDeserialized);
            builder.Append(tampaMapJavaScript);
            string countyTampaMapJavascript = JavaScriptBuilder.GetMapInsetCountiesJavaScript("tampaMap", tampaMapBoxPts, countyBaseLayersKml);
            builder.Append(countyTampaMapJavascript);

            javaScriptString = builder.ToString();//final javascript to render

            // check if the start up script is already registered with a key    
            if (!Page.ClientScript.IsStartupScriptRegistered("alert"))
            {        // since it is not registered, register the script        
                Page.ClientScript.RegisterStartupScript(
                    this.GetType(), "alert", javaScriptString, true);
            }

            this.Heading.InnerText = kmlDeserialized.Items[0].description;
            //this.PlanName.InnerText = kmlDeserialized.Items[0].plantype;

        }

        //*******************************************************************************************************




        public kmlDocument GetCountiesBaseLayers()
        {
            kmlDocument mapBaseKml = MapBase.GetCountiesBaseShapes();
            return mapBaseKml;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            mapControlPanel.Visible = false; //
        }


        protected void UploadButton_Click(object sender, EventArgs e)
        {
            if (FileUpload1.HasFile)
            {
                UploadStatusLabel.Text = "Please wait for Print Veiw to finish loading…";
                UploadStatusLabel.Font.Bold = true;
                UploadStatusLabel.Font.Size = 16;
                UploadStatusLabel.ForeColor = System.Drawing.Color.FromArgb(255, 192, 80, 77);
                //Need to unzip the kmz
                string fileExtension = Path.GetExtension(FileUpload1.FileName);
                string fileName = Path.GetFileNameWithoutExtension(FileUpload1.FileName);
                if (fileExtension == ".kml")
                {
                    //UploadStatusLabel.Text = "Please Wait for Print View to Finish Loading! Once it is loaded you will be notified by a pop-up and the appearance a print button!";
                    mapControlPanel.Visible = true;
                    kmlDeserialized = KMLSerialFunctions.DeserializeKML(FileUpload1.FileContent);
                    ConvertKMLToBingAjax();
                }
                if (fileExtension == ".kmz")
                {
                    mapControlPanel.Visible = true;
                    MemoryStream kmlFileStream = null;
                    if (ReadKmzStream(FileUpload1.FileContent, out kmlFileStream))
                    {
                        kmlDeserialized = KMLSerialFunctions.DeserializeKML(kmlFileStream);
                        ConvertKMLToBingAjax();
                    }
                }
            }
            else
            {
                // Notify the user that a file was not uploaded.
                UploadStatusLabel.Text = "You did not specify a file to upload. Please select a .kmz or .kml file!";
            }
        }

        public static bool ReadKmzStream(Stream KMZFileStream, out MemoryStream kmlFileStream)
        {
            ZipInputStream zipStream = new ZipInputStream(KMZFileStream);
            kmlFileStream = new MemoryStream();

            if (zipStream == null)
            {
                //Response.Write("Sorry, zip file is empty ");
                return false;
            }
            else
            {
                bool foundKML = false;
                bool foundDOJ = false;

                ZipEntry theEntry;
                string tmpEntry = String.Empty;
                while ((theEntry = zipStream.GetNextEntry()) != null)
                {
                    string fileName = theEntry.Name;

                    if (fileName != String.Empty)
                    {
                        if (theEntry.Name.Contains(".kml"))
                        {
                            StreamUtils.Copy(zipStream, kmlFileStream, new byte[4096]);
                            foundKML = true;
                        }
                        if (theEntry.Name.Contains(".doj"))
                        {
                            foundDOJ = true;
                        }
                    }
                }
                zipStream.Close();

                if (foundKML & foundDOJ)
                {

                    kmlFileStream.Seek(0, new SeekOrigin());
                    return true;
                }
                else
                {
                    return false;
                }
            }

        }

    }

}